var express = require('express');
var router = express.Router();
var db = require("../sqlcon");
/* GET home page. */

router.get('/group_add', function(req, res, next) {
    res.render('group_add');
});
router.get('/group_list', function(req, res, next) {
    var sql = "select * from groupes";
    db.query(sql,function(err,data){
        if(err){
            console.log(err);
        }
        else{
            res.render("group_list",{groupList:data});
        }
    })
});
router.post("/addgroup", function(req, res, next) {
    var groupName = req.body.groupname;
    var groupPower = req.body.data_send;
    console.log(groupPower);
    var sql = "insert into groupes (groupName,groupPower) value (?,?)";
    var sql_data = [groupName,groupPower];
    db.query(sql,sql_data,function (err,data) {
        if(err){
            console.log(err)
        }
        else{
            res.send("添加用户组成功");
        }
    });
});
router.post("/deletgroup",function (req,res,next) {
    var groupId = req.body.groupId;
    var sql="delete from groupes where groupId=?";
    db.query(sql,[groupId],function (err, data) {
        if (err) {
            console.log(err);
        }
        else{
            res.send("删除成功");
        }
    })
});
router.post("/delets",function (req,res,next) {
    var choosestr = req.body.choose;
    var choosee=choosestr.split(",");
    var chooselist="?";
    for(var i=0;i<choosee.length-1;i++){
        chooselist +=",?";
    }
    var sql="delete from groupes where groupId in ("+chooselist+")";
    db.query(sql,choosee,function (err, data) {
        if (err) {
            console.log(err);
        }
        else if (data.affectedRows==choosee.length) {
            res.send("删除成功");
        }
        else{
            res.send("删除异常");
        }
    })
});
router.post("/groupname",function(req,res,next){
    var groupName = req.body.search;
    var sql = "select * from groupes where groupName like '%"+groupName+"%'";
    db.query(sql,function(err,data){
        if(err){
            res.send("数据库操作异常");
        }
        else if(data.length > 0){
            res.render("group_list",{groupList:data});
        }
        else{
            res.send("用户组名不正确");
        }
    })
})
module.exports = router;
